/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved.
 *
 */
import {expect} from '@jest/globals';
import {iconv} from '@ohos/hvigor';
import fse from 'fs-extra';
import {runHvigorAsync} from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import {TestCaseBuilder} from '../../plugins/task-builder/task-case-builder';
import {ProjectBuildOption, TestCaseFun} from '../../plugins/task-builder/test-case';
import {TestTaskOptionBuilder} from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  }
};

const testfun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const moduleFile = await fse.readFile(`${projectRootPath}/build-profile.json5`);
  const entryPath = project.getModule('entry').moduleRootPath();
  await fse.ensureFile(`${entryPath}/src/main/ets/pages/test.ts`);
  const esStr = 'export function test() {\n' +
      '  let obj = { name: \'weakRefObj\' };\n' +
      '  let info = new WeakRef(obj);\n' +
      '}';
  await fse.writeFile(`${entryPath}/src/main/ets/pages/test.ts`, esStr, 'utf-8');
  const indexStr = 'import {test} from \'./test\'\n';
  const indexFile = await fse.readFile(`${entryPath}/src/main/ets/pages/Index.ets`);
  const indexFileStr = iconv.decode(indexFile, 'utf-8');
  await fse.writeFile(`${entryPath}/src/main/ets/pages/Index.ets`, indexStr + indexFileStr, 'utf-8');
  // 去掉文件中多余的 ,
  const str = iconv.decode(moduleFile, 'utf-8').replace(/(,[\r\n]\s+[}|\]])/g, ($1) => $1.slice(1));
  const moduleObj = JSON.parse(str);
  // 配置ESVersion
  moduleObj.app.products[0].buildOption = {
    arkOptions: {
      tscConfig: {
        targetESVersion: "ES2017"
      }
    }
  };
  await fse.writeFile(`${projectRootPath}/build-profile.json5`, JSON.stringify(moduleObj, null, 2), 'utf-8');
  // 执行hap构建
  const commonCommand = '--mode module -p product=default assembleHap --analyze=normal --parallel --incremental --daemon'.split(' ');
  try {
    await runHvigorAsync(project.projectRootPath(), commonCommand);
    // 正常路径走不到这里，预判一个异常
    expect('测试场景执行异常抵达此处').toEqual('测试场景执行正常不该抵达此处');
  } catch (e: any) {
    if (e.constructor.name === 'JestAssertionError') {
      throw e;
    }
    record.addStep('targetESVersion为2017全量构建，构建失败', {
      stdout: e.stdout,
      stderr: e.stderr
    })
    expect(e.stderr).toContain('ERROR: ArkTS Compiler Error');
    expect(e.stderr).toContain('Cannot find name \'WeakRef\'');
  }


  // 修改targetESVersion增量构建
  moduleObj.app.products[0].buildOption = {
    arkOptions: {
      tscConfig: {
        targetESVersion: "ES2021"
      }
    }
  };
  await fse.writeFile(`${projectRootPath}/build-profile.json5`, JSON.stringify(moduleObj, null, 2), 'utf-8');
  const resultIncre = await runHvigorAsync(project.projectRootPath(), commonCommand);
  record.addStep('修改targetESVersion为2021增量构建，构建成功', resultIncre);
  expect(resultIncre.stdout).toContain('BUILD SUCCESSFUL');

  // 再次修改targetESVersion增量构建
  moduleObj.app.products[0].buildOption = {
    arkOptions: {
      tscConfig: {
        targetESVersion: "ES2017"
      }
    }
  };
  await fse.writeFile(`${projectRootPath}/build-profile.json5`, JSON.stringify(moduleObj, null, 2), 'utf-8');
  try {
    await runHvigorAsync(project.projectRootPath(), commonCommand);
    // 正常路径走不到这里，预判一个异常
    expect('测试场景执行异常抵达此处').toEqual('测试场景执行正常不该抵达此处');
  } catch (e: any) {
    if (e.constructor.name === 'JestAssertionError') {
      throw e;
    }
    record.addStep('修改targetESVersion为2017增量构建，构建失败', {
      stdout: e.stdout,
      stderr: e.stderr
    })
    expect(e.stderr).toContain('ERROR: ArkTS Compiler Error');
    expect(e.stderr).toContain('Cannot find name \'WeakRef\'');
  }

}



TestCaseBuilder.builder()
  .caseName('TARGET_ES_VERSION_E2E_TEST')
  .description('targetESVersion的e2e用例')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.AR).build())
  .testFun(testfun)
  .load();
